package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)


var upGrader = websocket.Upgrader{
	CheckOrigin: func (r *http.Request) bool {
		return true
	},
}

//webSocket请求ping 返回pong
func WsHanderFunc(c *gin.Context) {
	//升级get请求为webSocket协议
	h := http.Header{}
	for _, sub := range websocket.Subprotocols(c.Request) {
		if sub == "hey" {
			h.Set("Sec-WebSocket-Protocol", "hey")
			break
		}
	}
	ws, err := upGrader.Upgrade(c.Writer, c.Request, h)
	if err != nil {
		return
	}
	defer ws.Close()
	for {
		// 读取ws中的数据
		mt, message, err := ws.ReadMessage()
		if err != nil {
			break
		}
		if string(message) == "ping" {
			message = []byte("pong")
		}
		// 写入ws数据
		err = ws.WriteMessage(mt, message)
		if err != nil {
			break
		}
	}
}

func main() {
	r := gin.Default()
	r.GET("/ws", WsHanderFunc)
	r.Run("localhost:8080")
}
